package com.chuzhiyun.chengguoxy.network;

import android.text.TextUtils;

import com.chuzhiyun.chengguoxy.global.Config;
import com.chuzhiyun.chengguoxy.global.MyApplication;
import com.chuzhiyun.chengguoxy.utlis.TimeUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.cookie.store.CookieStore;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.RxSPTool;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.RequestBody;

@SuppressWarnings("unchecked")
public class NetService {
    private volatile static NetService mNetService;
    public static NetService getInstance() {
        if (mNetService == null) {
            synchronized (NetService.class) {
                if (mNetService == null) {
                    mNetService = new NetService();
                }
            }
        }
        return mNetService;
    }

    private NetService() {
        Gson gson = new Gson();
    }

    public void get(String url, StringNetCallback callback) {
        OkGo.<String>get(url)
                .headers(getHeader(url))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            int statusCode = response.code();
                            String t = callback.convertResponse(response);
                            callback.onSuccess(t,statusCode);
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                            callback.onError(throwable.getMessage());
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        callback.onError(response.getException().getMessage());
                    }
                });
    }

    public void getParam(String url,HashMap<String, String> param, StringNetCallback callback) {

        OkGo.<String>get(url)
                .headers(getHeader(url))
                .params(param)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            int statusCode = response.code();
                            String t = callback.convertResponse(response);
                            callback.onSuccess(t,statusCode);
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                            callback.onError(throwable.getMessage());
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        callback.onError(response.getException().getMessage());
                    }
                });
    }

    public void postParam(String url, HashMap<String, String> param, StringNetCallback callback) {

        OkGo.<String>post(url)
                .headers(getHeader(url))
                .isMultipart(true)
                .params(param)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            int statusCode = response.code();
                            String t = callback.convertResponse(response);
                            callback.onSuccess(t,statusCode);
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                            callback.onError(throwable.getMessage());
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        callback.onError(response.getException().getMessage());
                    }
                });
    }

    public void postFileWithParam(String url, HashMap<String,String> param, ArrayList<File>addFiles, StringNetCallback callback){

        OkGo.<String>post(url)
                .isMultipart(true)
                .headers(getHeader(url))
                .params(param)
                .addFileParams("addFiles",addFiles)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            int statusCode = response.code();
                            String t = callback.convertResponse(response);
                            callback.onSuccess(t,statusCode);
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                            callback.onError(throwable.getMessage());
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        callback.onError(response.getException().getMessage());
                    }
                });
    }

    public void putFileWithParam(String url, HashMap<String, String> param, ArrayList<File>addFiles, List<String> deleteFile,StringNetCallback callback){

        OkGo.<String>put(url)
                .isMultipart(true)
                .headers(getHeader(url))
                .params(param)
                .addUrlParams("deleteFiles",deleteFile)
                .addFileParams("addFiles",addFiles)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            int statusCode = response.code();
                            String t = callback.convertResponse(response);
                            callback.onSuccess(t,statusCode);
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                            callback.onError(throwable.getMessage());
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        callback.onError(response.getException().getMessage());
                    }
                });
    }

    public void putParam(String url, HashMap<String,String>param, StringNetCallback callback) {
        OkGo.<String>put(url)
                .headers(getHeader(url))
                .isMultipart(true)
                .params(param)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            int statusCode = response.code();
                            String t = callback.convertResponse(response);
                            callback.onSuccess(t,statusCode);
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                            callback.onError(throwable.getMessage());
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        callback.onError(response.getException().getMessage());
                    }
                });
    }

    public void patchParam(String url, HashMap<String,String>param, StringNetCallback callback) {
        OkGo.<String>patch(url)
                .headers("Authorization",Config.SP_TOKEN)
                .isMultipart(true)
                .params(param)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            int statusCode = response.code();
                            String t = callback.convertResponse(response);
                            callback.onSuccess(t,statusCode);
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                            callback.onError(throwable.getMessage());
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        callback.onError(response.getException().getMessage());
                    }
                });
    }

    public void postPunchWithParam(String url, HashMap<String,String> param, File fileStr, StringNetCallback callback){

        String fileName = TimeUtils.getTimeAndHorstSring();

        OkGo.<String>post(url)
                .isMultipart(true)
                .headers(getHeader(url))
                .params(param)
                .params("picture", fileStr, fileName)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            int statusCode = response.code();
                            String t = callback.convertResponse(response);
                            callback.onSuccess(t,statusCode);
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                            callback.onError(throwable.getMessage());
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        callback.onError(response.getException().getMessage());
                    }
                });
    }

    private HttpHeaders getHeader(String url){
        HttpHeaders headers = new HttpHeaders();
        HttpUrl httpUrl = HttpUrl.parse(url);
        Cookie.Builder builder = new Cookie.Builder();
        assert httpUrl != null;
        Cookie cookie = builder.name("token").value(RxSPTool.getString(MyApplication.self, Config.SP_TOKEN)).domain(httpUrl.host()).build();

        CookieStore cookieStore = OkGo.getInstance().getCookieJar().getCookieStore();
        cookieStore.saveCookie(httpUrl, cookie);
        android.util.Log.e("OkGo", cookieStore.getAllCookie().toString());

        String tokens = RxSPTool.getString(MyApplication.getmContext(),Config.SP_TOKEN);
        String CSRFToken = "X-CSRFToken";
        if (TextUtils.isEmpty(tokens)){
            CSRFToken = "";
        }else {
            CSRFToken = tokens;
            headers.put("X-CSRFToken",tokens);
        }
        headers.put("Referer",NetApi.Base_URL);
        return headers;
    }

    public <T>void postJson(String url,String json,INetCallback<T>callback)
    {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);

        OkGo.<String>post(url)
                .headers(getHeader(url))
                .upRequestBody(body)
                .isMultipart(true)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            int statusCode = response.code();
                            String t = (String) callback.convertResponse(response);
                            callback.onSuccess((T) t,statusCode);
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                            callback.onError(throwable.getMessage());
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        callback.onError(response.getException().getMessage());
                    }
                });

    }

    public <T>void putJson(String url,String json,INetCallback<T>callback)
    {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);

        OkGo.<String>put(url)
                .headers(getHeader(url))
                .upRequestBody(body)
                .isMultipart(true)
                .execute(new StringCallback() {
                    @SuppressWarnings("unchecked")
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            int statusCode = response.code();
                            String t = (String) callback.convertResponse(response);
                            callback.onSuccess((T) t,statusCode);
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                            callback.onError(throwable.getMessage());
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        callback.onError(response.getException().getMessage());
                    }
                });

    }

    public <T>void patchJson(String url,String json,INetCallback<T>callback)
    {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);

        OkGo.<String>patch(url)
                .headers(getHeader(url))
                .upRequestBody(body)
                .isMultipart(true)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            int statusCode = response.code();
                            String t = (String) callback.convertResponse(response);
                            callback.onSuccess((T) t,statusCode);
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                            callback.onError(throwable.getMessage());
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        callback.onError(response.getException().getMessage());
                    }
                });

    }

    public <T>void deleteJson(String url,String json,INetCallback<T>callback)
    {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);

        OkGo.<String>delete(url)
                .headers(getHeader(url))
                .upRequestBody(body)
                .isMultipart(true)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            int statusCode = response.code();
                            String t = (String) callback.convertResponse(response);
                            callback.onSuccess((T) t,statusCode);
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                            callback.onError(throwable.getMessage());
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        callback.onError(response.getException().getMessage());
                    }
                });

    }



    private String getToken(){
        String tokens = RxSPTool.getString(MyApplication.getmContext(),Config.SP_TOKEN);
        String CSRFToken = "X-CSRFToken";
        if (TextUtils.isEmpty(tokens)){
            CSRFToken = "";
        }else {
            CSRFToken = tokens;
        }
        return CSRFToken;
    }

}
